<template>
  <div class="create-order router-view">
    <s-Header name="生成订单" :nomore="false" :noback="false" @callback="deleteLocal" ></s-Header>
    <van-cell is-link class="header-info" @click="toAddress">
      <div slot="title" class="order-info">
        <p class="custom-title">{{state.address.userName}}</p>
        <p type="primary">{{state.address.userPhone}}</p>
      </div>
      <p class="address"> {{ state.address.provinceName }} {{ state.address.cityName }} {{ state.address.regionName }} {{ state.address.detailAddress }}</p>
    </van-cell>
    <!-- 商品列表 -->
    <div class="product-list">
      <div class="product-content" v-for="item in state.cartList" :key="item.orderNo">
        <div class="good-img">
          <img :src="$filters.prefix(item.goodsCoverImg)" alt="">
        </div>
        <div class="product-info">
          <div class="top-info">
            {{item.goodsName}}
          </div>
          <div class="bottom-info">
            <span class="price">¥{{item.sellingPrice}} <i>x{{ item.goodsCount }}</i></span>
          </div>
        </div>
      </div>
    </div>
    <!-- 底部生成订单 -->
    <div class="pay-wrap">
      <div class="price">
        <span>商品金额</span>
        <span>¥{{ total }}</span>
      </div>
      <van-button @click="handleCreateOrder" class="pay-btn" color="#1baeae" type="primary" block>生成订单</van-button>
    </div>
    <!-- popup选中支付方式 -->
    <van-popup
      :show="state.showPay"
      position="bottom"
      round
      :style="{ height: '28%' }"
      @close="close"
    >
      <template #default>
        <div :style="{ width: '90%', margin: '0 auto', padding: '50px 0' }">
          <van-button :style="{ marginBottom: '10px' }" color="#1989fa" block @click="handlePayOrder(1)">支付宝支付</van-button>
          <van-button color="#4fc08d" block @click="handlePayOrder(2)">微信支付</van-button>
        </div>
      </template>
    </van-popup>
  </div>
</template>
<script setup>
  import { useRoute, useRouter } from 'vue-router'
  import { reactive, ref, isRef, isReactive,nextTick, onUnmounted, onMounted, computed   } from 'vue'
  import { showSuccessToast, showFailToast, showLoadingToast, closeToast } from 'vant'
  import { setLocal, getLocal } from '@/common/js/utils'
  import { getHome } from '@/service/home'
  import NavBar from '@/components/NavBar.vue'
  import sHeader from '@/components/SimpleHeader.vue'
  import { getByCartItemIds } from '@/service/cart'
  import { getDefaultAddress, getAddressDetail } from '@/service/address'
  import { createOrder, payOrder } from '@/service/order'

  const router = useRouter();
  const route = useRoute();
  console.log('router...',router,route)

  const state = reactive({
    show:false,
    address: {}, // 收货地址
    cartList: [], // 商品列表
    showPay: false, // popupFlag
    orderNo:'', // 生成订单号
    cartItemIds: [], // 产品号列表
  })

  const total = computed(() => {
    return state.cartList.reduce((pre,cur)=> pre + (cur.goodsCount * cur.sellingPrice),0)
  })

  onMounted(()=>{
    init()
  })

  // 从购物过来query携带cartItemIds,当从地址栏过来时候,从缓存中获取
  const init = async () => {
    showLoadingToast({ message: '加载中...', forbidClick: true });
    const { addressId, cartItemIds } = route.query
    // parse选中商品id列表
    const _cartItemIds = cartItemIds ? JSON.parse(cartItemIds) : JSON.parse(getLocal('cartItemIds'))
    setLocal('cartItemIds', JSON.stringify(_cartItemIds))
    const { data: list } = await getByCartItemIds({ cartItemIds: _cartItemIds.join(',') })
    // url过来未携带地址时候取默认地址d时候取默认地址
    const { data: address } = addressId ? await getAddressDetail(addressId) : await getDefaultAddress()
    if (!address) {
      router.push({ path: '/address' })
      return
    }
    state.cartList = list
    state.address = address
    closeToast()
  }

  // 生成对应订单号 用于支付
  const handleCreateOrder = async ()=>{
    const params = {
      addressId: state.address.addressId,
      cartItemIds: state.cartList.map(item => item.cartItemId)
    }
    const { data } = await createOrder(params)
    setLocal('cartItemIds', '')
    state.orderNo = data;
    state.showPay = true;
  } 

  // 通过订单号来支付生成订单
  const handlePayOrder = async (type) => {
    await payOrder({ orderNo: state.orderNo, payType: type })
    showSuccessToast('支付成功')
    setTimeout(() => {
      router.push({ path: '/order' })
    }, 2000)
  }

  // 返回是清空
  const deleteLocal = () => {
    setLocal('cartItemIds', '')
  }

  const close = () => {
    router.push({ path: '/order' })
  }

  // 跳转选择收货地址
  const toAddress = () => {
    const { cartItemIds } = route.query
    router.push({ path: '/address', query: {
      from:'create-order',
      cartItemIds:JSON.stringify(cartItemIds)
    } })
  }
  
</script>
  

<style lang="less" >
   
</style>
<style lang="less" scope>
  .router-view{
    width: 100%;
    height: auto;
    position: absolute;
    top: 0;
    bottom: 0;
    margin: 0 auto;
  }
  .create-order{
    background: #f9f9f9;
    height: 100%;
    .header-info{
      display: flex;
      align-items: center;
      text-align:left;  
      &::after{
        content: '';
        display: inline-block;
        position: absolute;
        left: 0;
        right: 0;
        height: 3px;
        background: repeating-linear-gradient(-45deg, #ff6c6c, #ff6c6c 20%, transparent 0, transparent 25%, #1989fa 0, #1989fa 45%, transparent 0, transparent 50%);
        background-size: 2.13333rem;
      }
      padding: 5px 10px 5px 20px;
      .van-cell__value{
        color: #222333;
        text-align:left;  
        padding-right: 10px;
        line-height: 18px;
        .order-info{
          padding: 15px;
          padding:4px 0px;
        }
        .address{
          padding-bottom:4px;
        }
      }
    }
    .product-list{
      padding-bottom:110px;
      .product-content{
        height:110px;
        display: flex;
        align-items: center;
        padding: 5px;
        border-radius: 4px;
        margin: 10px;
        background: #fff;
        box-shadow: 0.02667rem 0.02667rem 0.10667rem 0 #ccc;
        .van-checkbox{
          flex-basis: 40px;
        }
        img{
          width: 100px;
          height: 100px;
        }
        .product-info{
          height: 100%;
          width: 100%;
          padding-top:6px;
          padding-bottom:6px;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          padding-left: 10px;
          .top-info{
            font-size:12px;
            font-family: Avenir, Helvetica, Arial, sans-serif;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            color: #2c3e50;
            text-overflow: ellipsis;
            -webkit-line-clamp: 3;
            line-break: anywhere;
            -webkit-box-orient: vertical;
            display: -webkit-box;
            overflow: hidden;
          }
          .bottom-info{
            width: 100%;
            display: flex;
            flex:1;
            justify-content: space-between;
            align-items: flex-end;
            .price{
              font-size: 15px;
              color: red;
              line-height: 28px;
              i{
                font-size: 13px;
                padding-left: 2px;
                color: #2c3e50;
              }
            }
          }
        }
      }
    }
    
    .pay-wrap{
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      background: #fff;
      border-radius: 8px 8px 0px 0px;
      padding:10px;
      .price{
        display: flex;
        justify-content: space-between;
        padding: 6px 6px;
        font-size: 20px;
        span:last-child{
          color:red;
        }
      }
    }
  }

</style>